#ifndef HTTPSERVER_H
#define HTTPSERVER_H

#include <cstdio>
#include <ctime>
#include <string>
#include "messageheader.h"
#include "httputil.h"
using std::string;
typedef MessageHeader ServerConf;

class HTTPServer
{
public:

    enum Status {
        ServerListening,
        ServerClosed,
        nStatus
    };

    HTTPServer();
    // load configuration file.
    bool loadConf(const string& confFilePath);
    // useless for this single-thread version
    Status getCurrentStatus() const;
    // will block in this version
    bool listen();
    // create socket and bind
    bool setup(int port);
    // since setup blocks, we should call close()
    // on SIGKILL handler
    void close();
    void setLog(FILE* file);
private:
    const static string SERVER;
    Status m_status;
    ServerConf m_conf;
    int m_port;
    FILE* m_log;
    int m_sockfd;

    void log(const char* fmt, ...);
    bool writeResponse(HTTPUtil::HTTPMethod method, const MessageHeader& headers, const string& path, int sock);
    bool notfound(int sock);
    string getGMT() const;
    string getmime(const string& filePath) const;

    // This two methods will send content and
    // Content-Length field, including the blank line
    // this imples headers are over. So ensure calling
    // them only at the end of headers
    bool writeContent(const string& content, int sock);
    bool writeContent(int fd, int sock, int length);
};

#endif
